package com.jackey.sms.session;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**
 * @author 小伟
 * @version V1.0
 * @Package com.jackey.sms.session
 * @date 2020/12/20 18:12
 * @Copyright © 2020-2021 郑州恒星科技有限责任公司
 * 自定义session会话管理器
 */
public class CustomSessionManager extends DefaultWebSessionManager {
    /**
     *   * 头信息中具有sessionid
     *   *   请求头：Authorization： sessionid
     *   *
     *   * 指定sessionId的获取方式
     *   
     */
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String id = WebUtils.toHttp(request).getHeader("Authorization");
        if (!StringUtils.hasLength(id)) {
            //为空时生成一个sessionId
            return super.getSessionId(request, response);
        } else {
            //返回sessionId；
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
                    "header");
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);

            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID,
                    Boolean.TRUE);
            return id;
        }
    }
}
